package com.gxgeek.publish_and_subscribe;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @author gaoxing
 * @create 2018-05-16 下午5:49
 */
public class ReceiveLogs {
    private static final String EXCHANGE_NAME = "logs";
    private final static String QUEUE_NAME = "logs_queue_1";//队列名称

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);
        //每次连接创建新的队列直接bind EXCHANGE 创建随机队列
//        String QUEUE_NAME = channel.queueDeclare().getQueue();
        // 声明队列 显示 申明
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);

        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "");

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println(" [x] Received '" + message + "'");
                try {
                    doWork(message);
                } finally {
                    System.out.println(" [x] Done");
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }

            }
        };
        channel.basicConsume(QUEUE_NAME, false, consumer);
    }

    private static void doWork(String task) {
//        for (char ch : task.toCharArray()) {
//            if (ch == '.') {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException _ignored) {
            Thread.currentThread().interrupt();
        }
//            }
//        }
    }

}
